/**
 * Gère le chargement asynchrone des contenus
 *  - une vue par contenu
 *  - dynamisation JS des contenus / vue (fade, animations etc.)
 *  - mise en cache de chaque contenu 
 *  - decache quand besoin
 *  - animation de transfert entre chaque changement de contenu
 */

/**
 * Classe abstraite View
 * Gère les vues
 *//*
var View = $.inherit(
 
{
  name: null,
  href: null,
  
  __constructor: function(name, href){ 
    this.name = name;
    this.href = href;
    
    if ( !this.find() ) {
      this.preload(false);
    }
    else {
      this.dynamics();
    }
  },
  
  find: function() { 
    var divName = 'div.page#' + this.name;
    
    // Affiché en ce moment
    var div = $('#container '+ divName);
    if ( div.size() > 0 ) {
      return div;
    }
    
    // En cache
    div = View.cache.find(divName);
    if ( div.size() > 0 ) {
      return div;
    }    
   
    return false;
  },
  
  preload: function(sync) { 
    var sync =  ( sync == undefined ) ? true : sync; // Default synchron   
    var _this = this;
    var result = null;
    echo(this.href);
    $.ajax({
      async: !sync,
      type: 'POST',
      url: this.href,
      data: {
        ajax:'true'
      },
      dataType: 'html',
      success: function(data) {
        result = $(data);
        _this.appendCache(result);
        _this.dynamics();
      }
    });
   
    return result;
  },
  
  findWithPreload: function() { 
    var find = this.find();   
    if ( !find ) {
      return this.preload(true);      
    }
    else {
      return find;
    }   
  },
  
  appendCache: function(item) {
    View.cache.append(item);
  },
  
  appendContainer: function(item) {
    $('#container').append(item);
  },
  
  display: function() {
    var _this = this;
    var contents = this.findWithPreload();
    var oldContents = $('#container .page');
    
    if ( contents.attr('id') != oldContents.attr('id') ) {
      oldContents.fadeOut(150, function(){
        _this.appendContainer(contents.hide());
        contents.fadeIn(400);
        _this.appendCache(oldContents);    
      });
    }
    
  },
  
  dynamics: function() {},
  cache: function() {}
}, 
/* 
{
  cache: null, 
  views: {},
  init: function() {
    if ( this.cache == null ) {
      this.cache = $('#view-cache');
      if ( this.cache.size() == 0 ) {
        this.cache = $('<div id="view-cache"></div>').appendTo('body').hide();
      }
    }
    
    // Listen menu changed
    $('#menu').bind('status', function(e, args){
      View.display(args.item.attr('name'));
    });
  },
  load: function(name, href) {
    var name = name || 'home',
    href = href || null;    
    try { echo("create "+name);
      this.views[name] = eval("new " + name.ucfirst() + "(name, href);");    
    }
    catch(exception) {error(exception);}
  },
  
  display: function(name) {
    this.views[name].display();
  }  
 
});


var Templates = {
  Home: {
    
  }
};

var Home = $.inherit(View, {
  dynamics: function() {
    var homeItems = $('#home a').fadeOthers();
    homeItems.bind('click', function(){
      $('#menu li a:eq('+homeItems.index($(this))+')').trigger('click');
      return false;
    });
  }
});


var Evenementiel = $.inherit(View, {
  dynamics: function() {
    $('#evenementiel a').fadeOthers().bind('click', function(){ 
      View.display($(this).attr('name'));
      return false;
    }).each(function(){
      View.load($(this).attr('name'), $(this).attr('href'));
    });    
  }
});

var Travaux = $.inherit(View, {
  });


var Ceremonies = $.inherit(View, {
  });

var Portraits = $.inherit(View, {
  });

var Bio = $.inherit(View, {
  });
  
  
var Galerie = $.inherit(View, {
  dynamics: function() {
      this.__base();
      
  }
});

var EvenementielDanse = $.inherit(Galerie, {
  dynamics: function() {
     this.__base(); // Call parent dynamics
  }
});
*/


var Cache = {
  elem: null,
  ajax: function(name, url, sync) {
    var async =  ( sync == undefined ) ? true : !sync; // Default asynchron   
    var result = null;
    $.ajax({
      async: async,
      type: 'POST',
      url: url,
      data: {
        ajax:'true'
      },
      dataType: 'html',
      success: function(data) {
        result = $(data);
        Cache.set(result);
        Cache.init(name);
      }
    });
    return result;
  },
  
  /*
   * Pré charge un contenu
   */
  preload: function(templateName, templateUrl) {
    var elem = Cache.elem.find('#' + templateName);
    if ( elem.size() <= 0 ) {
      Cache.ajax(templateName, templateUrl);
    }    
  },
  
  /*
   * Charge en temps réel (synchrone) un contenu
   */
  load: function(templateName, templateUrl) {
    return Cache.ajax(templateName, templateUrl, true);
  },
  
  /*
   * Récupère un contenu
   */
  get: function(templateName, templateUrl) {
    var elem = Cache.elem.find('#' + templateName);
    if ( elem.size() <= 0 ) {
      elem = Cache.load(templateName, templateUrl);
    }
    return elem;
  },
  
  /*
   * Met dans le cache un élément
   */
  set: function(bloc) {
     Cache.elem.append(bloc);     
  },
  
  /*
   * Initialise (JS...) un bloc
   */
  init: function(templateName) {
    var initFunction = View.TEMPLATES[templateName];
    if ( initFunction != undefined ) {
      initFunction.call();
    }
  }
};


/* 
 * 
 * View pages, cache...
 * 
 */
var View = {
  init: function() { 
    // Gestion du cache
    if ( Cache.elem == null ) {
      Cache.elem = $('#view-cache');
      if ( Cache.elem.size() == 0 ) {
        Cache.elem = $('<div id="view-cache"></div>').appendTo('body').hide();
      }
    }
    
    // Changement sur le menu
    $('#menu').bind('status', function(e, args){
      View.display(args.item.attr('name'), args.item.attr('href'));
    });   
          
    $('#menu a').add('#logo').each(function(){
      Cache.preload($(this).attr('name'), $(this).attr('href'));
    });
  },
  
  /*
   * Change de page
   */
  display: function(templateName, templateUrl) {
    var contents = Cache.get(templateName, templateUrl); 
    var oldContents = $('#container .page');
    
    if ( contents.attr('id') != oldContents.attr('id') ) {
      oldContents.fadeOut(150, function(){
        View.set(contents.hide());
        contents.fadeIn(400);
        Cache.set(oldContents);    
      });
    }    
  },
  
  /*
   * Met un contenu dans le container
   */
  set: function(contents) {
    $('#container').append(contents);
  },
  
  TEMPLATES: {
    home: function() {
      var homeItems = $('#home a').fadeOthers();
      homeItems.bind('click', function(){
        $('#menu li a:eq('+homeItems.index($(this))+')').trigger('click');
        return false;
      });
    },

    evenementiel: function() {
      $('#evenementiel a').fadeOthers().bind('click', function(){ 
        View.display($(this).attr('name'), $(this).attr('href'));
        return false;
      }).each(function(){
        Cache.preload($(this).attr('name'), $(this).attr('href'));
      });    
    },
    
    galerie: function() {
      $('.page.galerie ul').galleryView({
        // General Options
		transition_speed: 1000, 		//INT - duration of panel/frame transition (in milliseconds)
		transition_interval: 5000, 		//INT - delay between panel/frame transitions (in milliseconds)
		easing: 'linear', 				//STRING - easing method to use for animations (jQuery provides 'swing' or 'linear', more available with jQuery UI or Easing plugin)
		
		// Panel Options
		show_panels: true, 				//BOOLEAN - flag to show or hide panel portion of gallery
		show_panel_nav: true, 			//BOOLEAN - flag to show or hide panel navigation buttons
		enable_overlays: true, 			//BOOLEAN - flag to show or hide panel overlays
		panel_width: 900, 				//INT - width of gallery panel (in pixels)
		panel_height: 500, 				//INT - height of gallery panel (in pixels)
		panel_animation: 'crossfade', 		//STRING - animation method for panel transitions (crossfade,fade,slide,none)
		panel_scale: 'crop', 			//STRING - cropping option for panel images (crop = scale image and fit to aspect ratio determined by panel_width and panel_height, fit = scale image and preserve original aspect ratio)
		overlay_position: 'bottom', 	//STRING - position of panel overlay (bottom, top)
		pan_images: false,				//BOOLEAN - flag to allow user to grab/drag oversized images within gallery
		pan_style: 'drag',				//STRING - panning method (drag = user clicks and drags image to pan, track = image automatically pans based on mouse position
		pan_smoothness: 10,				//INT - determines smoothness of tracking pan animation (higher number = smoother)
		
		// Filmstrip Options
		start_frame: 1, 				//INT - index of panel/frame to show first when gallery loads
		show_filmstrip: true, 			//BOOLEAN - flag to show or hide filmstrip portion of gallery
		show_filmstrip_nav: true, 		//BOOLEAN - flag indicating whether to display navigation buttons
		enable_slideshow: false,			//BOOLEAN - flag indicating whether to display slideshow play/pause button
		autoplay: false,				//BOOLEAN - flag to start slideshow on gallery load
		show_captions: false, 			//BOOLEAN - flag to show or hide frame captions	
		filmstrip_size: 6, 				//INT - number of frames to show in filmstrip-only gallery
		filmstrip_style: 'scroll', 		//STRING - type of filmstrip to use (scroll = display one line of frames, scroll filmstrip if necessary, showall = display multiple rows of frames if necessary)
		filmstrip_position: 'top', 	//STRING - position of filmstrip within gallery (bottom, top, left, right)
		frame_width: 100, 				//INT - width of filmstrip frames (in pixels)
		frame_height: 60, 				//INT - width of filmstrip frames (in pixels)
		frame_opacity: 0.6, 			//FLOAT - transparency of non-active frames (1.0 = opaque, 0.0 = transparent)
		frame_scale: 'crop', 			//STRING - cropping option for filmstrip images (same as above)
		frame_gap: 8, 					//INT - spacing between frames within filmstrip (in pixels)
		
		// Info Bar Options
		show_infobar: false,				//BOOLEAN - flag to show or hide infobar
		infobar_opacity: .7				//FLOAT - transparency for info bar
      });
    },
    
    evenementielDanse: function() { View.TEMPLATES.galerie(); }
  }
}